local cjson = require "cjson"
local req = require "dispatch.req"
local result = require "common.result"
local template = require("resty.template")
local _lfs = require ("lfs")

local _M = {}

local function getType(path)
  return _lfs.attributes(path).mode
end

local function getSize(path)
  return _lfs.attributes(path).size
end

local function getInfo(str)
  local info = {}
  local f, l = str:find("[0-9]*-[%d]*-[%d]*-")
  if l then
    info.date = str:sub(f, l-1)
    ngx.log(ngx.INFO, "date:" .. info.date)
    local _f, _l = str:find("%.")
    info.file = str:sub(l+1, _f-1)
    info.title = str:sub(l+1, _f-1)
    ngx.log(ngx.INFO, "file:" .. info.file)
    info.fileType = str:sub(_l+1, -1)
    ngx.log(ngx.INFO,"file type:" .. info.fileType)
  else
    return nil
  end
  return info
end

local function getJson(path)
  local post = {}

  for file in _lfs.dir(path) do
    local p = path .. "/" .. file
    if file ~= "." and file ~= '..' then
      if getType(p) == "file" then
        local f = getInfo(file)
        if f then
          f.path = p
          table.insert(post, f)
        end
      end
    end
  end
  table.sort(post, function (l, r)
    if l.date ~= r.date then
    	return l.date > r.date --名称升序排列
    end
    return false
  end)
  return post
end


-- 主页
function _M:index()
    local posts = getJson('/home/sniper/nginx/html/_posts')
    -- for k,v in ipairs(posts) do
    --     ngx.log(ngx.INFO, k," " .. v.date .. v.title .. v.path)
    -- end
    -- ngx.log(ngx.ERR, "failed to new upload: ")
    local page = {}
    page.title = "王晋蜀的个人空间"
    page.description = "这里将深入探讨编程技术，包括linux, c, c++, rust等语言，vim，emacs, 架构设计等。:)"
	local context = {posts = posts, page = page}
	template.render("blog/index.htm", context)
end

-- 获取单个文章
function _M:detail()
	local args = req.getArgs()
	local articleId = args["articleId"]

	if articleId == nil or articleId == "" then
		ngx.say(cjson.encode(result:error("ID为空")))
		return
	end
    local posts = getJson('/home/sniper/nginx/html/_posts')
    ngx.log(ngx.INFO,"articleId: ", articleId)
	local entity = {}
	entity.path = posts[tonumber(articleId)].path
    ngx.log(ngx.INFO,"path: ", posts[tonumber(articleId)].path)
    local file = io.open (entity.path, r)
    local s = file:read("*a")
    print(string.gsub(s, "`", "\\`"))
    entity.content = string.gsub(s, "`", "\\`")
    local page = {}
    page.title = posts[tonumber(articleId)].title
    page.description = posts[tonumber(articleId)].date
	local context = {entity = entity, page = page}
	template.render("blog/article.html", context)
end

function _M:post()
  local args = {}
  local request_method = ngx.var.request_method
  local client_ip = ngx.var.remote_addr   -- ngx lua api  ngx.var 表示获取nginx自己的值，remote_addr为nginx中的客户端地址
  local user_agent = ngx.req.get_headers()['user-agent'] or ''    -- 读取 post请求的头部信息，如果未读到则为空
  if request_method == "GET" then
      args = ngx.req.get_uri_args()
  elseif request_method == "POST" then
      ngx.req.read_body()
      args = ngx.req.get_post_args()
      -- args = ngx.req.get_body_data()
      -- ngx.say("post body :", args)
  end
  ngx.log(ngx.INFO, "args info: ", args.info)
  if not args or not args.info then       -- 如果post请求的参数有为空的则通过 HTTP_BAD_REQUEST 抛出 400
      ngx.exit(ngx.HTTP_BAD_REQUEST)      -- ngx lua api
  end

  local response = {}
  response.info = args.info
  response.ip = client_ip
  response.user_agent = user_agent
  response.company = "上海移柯通信股份有限公司成都分公司"
  ngx.say(cjson.encode(response))
end

function _M:test()
	template.render("blog/header.html", {})
end

return _M
